<?php

namespace app\admin\controller;

use app\admin\controller\CommonController;
use app\admin\model\Item;
use app\admin\model\ItemClass;
use think\Validate;
use think\Db;
use app\util\Utils;
use app\admin\model\ItemImg;
use app\admin\model\Yuyue;
use app\admin\model\Order;
use app\admin\model\OrdPro;
use app\admin\model\YuyueCopy;
use app\admin\model\Overgroup;
use app\admin\model\OvergroupItem;
use app\admin\model\Miaosha;
use app\admin\model\ProgramRefund;
use app\admin\model\ItemToGoods;
use app\admin\model\Store;
use app\admin\model\ItemProcess;
use app\admin\model\Custom;
use app\admin\model\OrderYimei;
use app\admin\model\Imeigroup;
use think\Cache;

class ItemController extends CommonController {
    /*
     * 项目列表
     * author xfwed 
     * date 2019.09.09
     */

    public function itemList() {
        $admin = new Item();
        $item_type = input('param.item_type');
        $item_name = input('param.item_name');
        $perPage = input('param.perPage');
        $page = input('param.page');
        $isDel = input('param.is_del');
        $status = input('param.status');
        $is_new = input('param.is_new');
        $is_yimei = input('param.is_yimei');//1是2否为医美 项目
        $is_imeigroup = input('param.is_imeigroup');//1是2否为I美套餐
        $sku = input('param.sku');
        $type = input('param.type'); //-1全部0普通项目 1热玛吉 2美修斯 3伊丽丝白4华晟澳源 
        $is_special = input('param.is_special');//是否特色 0全部 1.是 2.否
        $issue_type = input('param.issue_type');//1祛痘2祛斑3祛皱4瘦身5其他  改为  1.敏感修护2.晒后修护3.激素脸4.紧致毛孔5.红血丝6.抗衰祛皱7.淡化色斑8.消炎祛痘9其他	
        $tag = input('param.tag');//拍照测肤完根据此标签推荐项目 1.敏感 2干燥缺水3油脂旺盛4黑头毛孔5痘痘6色素斑7细纹8黑眼圈9眼袋10肤色暗沉	
        
        $status = isset($status) ? $status : 1;
        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        if ($item_type) {
            $where['i.item_type'] = $item_type;
        }
        if ($item_name) {
            $where['i.item_name'] = ['like', '%' . $item_name . '%'];
        }
        if ($isDel) {
            $where['i.is_del'] = $isDel;
        }

        if ($status) {
            $where['i.status'] = $status;
        }
        
        if ($is_new) {
            $where['i.is_new'] = $is_new;
        }
        if ($is_yimei) {
            $where['i.is_yimei'] = $is_yimei;
        }
        
        if ($is_imeigroup) {
            $where['i.is_imeigroup'] = $is_imeigroup;
        }
        
        if($sku){
            $where['i.sku'] = $sku;
        }
        
        if($type){
            if($type != -1){
                $where['i.type'] = $type;
            }
        }  else {
            if($type == 0){
                $where['i.type'] = $type;
            }
        }
        
        if ($is_special) {
            $where['i.is_special'] = $is_special;
        }
        if($issue_type){
            if($issue_type == -1){
                $where['i.issue_type'] = ['<>',0];
            }  else {
                $where['i.issue_type'] = $issue_type;
            }
        }
        if($tag){
            if($tag == -1){
                $where['i.tag'] = ['<>',0];
            }  else {
                $where['i.tag'] = $tag;
            }
        }

//      $where['i.is_del'] = 1;
        $where = isset($where) ? $where : [];
        $itemList = Item::alias('i')
                ->join('item_class c', 'i.item_type = c.id', 'LEFT')
                //->join('item_class c2', 'i.type = c2.id', 'LEFT')
//                ->join('yuyue y', 'i.id = y.item_id', 'INNER')
//                ->distinct(true)
                ->field('i.id,i.type,i.item_name,i.item_img,i.item_price,i.special_money,i.is_del,i.add_time,i.visit_count,i.sale_money,i.status,i.why,i.add_name,i.audit_name,i.audit_time,i.is_new,i.is_yimei,i.is_imeigroup,c.name item_type,i.sku,i.is_special,i.issue_type,i.tag')
                ->where($where)
                ->order('id desc')
                ->paginate($perPage);

        foreach ($itemList as $k => $v) {//,count(y.id) ser_num,count(distinct y.ctm_id) ser_ctmnum
            $itemList[$k]['ser_num'] = Yuyue::where('item_id', '=', $v['id'])->where('status', 'in', '4,7,8')->count();
            $itemList[$k]['ser_ctmnum'] = Yuyue::where('item_id', '=', $v['id'])->where('status', 'in', '4,7,8')->group('ctm_id')->count();
        }
        return $this->ajaxReturn(0, '查询成功', $itemList);
    }

    /*
     * 项目分类
     * author xfwed 
     * date 2019.09.09
     */

    public function itemClassList() {
        $type = input('param.type');
        $page = isset($type) ? $type : 0;
        $itemClassList = ItemClass::where('type', '=', $type)
                ->where('status', '=', 1)
                ->where('pid', '=', 0)
                ->order('sort asc')
                ->select();
        if ($type == 0) {
            foreach ($itemClassList as $k => $v) {
                $pdata = ItemClass::where('pid', '=', $v['id'])
                        ->where('status', '=', 1)
                        ->order('sort asc')
                        ->select();
                foreach ($pdata as $key => $val) {
                    $saleMoney = Item::where('item_type', '=', $val['id'])->sum('sale_money');
                    $pdata[$key]['saleMoney'] = $saleMoney;

                    $sellCount = Item::where('item_type', '=', $val['id'])->sum('sell_count');
                    $pdata[$key]['sellCount'] = $sellCount;
                }
                $itemClassList[$k]['pdata'] = $pdata;
            }
        } elseif ($type == 1) {
            foreach ($itemClassList as $k => $v) {

                $saleMoney = Item::where('type', '=', $v['id'])->sum('sale_money');
                $itemClassList[$k]['saleMoney'] = $saleMoney;

                $sellCount = Item::where('type', '=', $v['id'])->sum('sell_count');
                $itemClassList[$k]['sellCount'] = $sellCount;
            }
        }
        return $this->ajaxReturn(0, '查询成功', $itemClassList);
    }

    /*
     * 添加项目分类
     * author xfwed 
     * date 2019.09.09
     */

    public function addItemClass() {
        $rule = [
            'type' => 'require',
            'pid' => 'require',
            'name' => 'require',
            'sort' => 'require',
        ];
        $msg = [
            'type.require' => '类型必须',
            'pid.require' => '级别必须',
            'name.require' => '名称必须',
            'sort.require' => '排序必须',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);

        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }

        $data['type'] = $all['type'];
        $data['pid'] = $all['pid'];
        $data['name'] = $all['name'];
        if ($all['pid'] == 0) {
            $data['level'] = 1;
        } else {
            $data['level'] = 2;
        }
        $data['icon'] = $all['icon'];
        $data['sort'] = $all['sort'];
        $data['status'] = 1;
        $data['add_time'] = date('Y-m-d H:i:s');
        $add = Db::name('item_class')->insert($data);
        if ($add) {
            return $this->ajaxReturn(0, '添加成功', null);
        } else {
            return $this->ajaxReturn(3, '添加失败', null);
        }
    }

    /*
     * 修改项目分类
     * author xfwed 
     * date 2019.09.10
     */

    public function saveItemClass() {
        $requestType = input('param.requestType');
        $id = input('param.id');
        if ($requestType == 1) {//1修改前获取信息 2提交修改
            $itemClassRow = ItemClass::where('id', '=', $id)->find();
            return $this->ajaxReturn(0, '查询成功', $itemClassRow);
        } else {
            $rule = [
                'type' => 'require',
                'pid' => 'require',
                'name' => 'require',
                'sort' => 'require',
            ];
            $msg = [
                'type.require' => '类型必须',
                'pid.require' => '级别必须',
                'name.require' => '名称必须',
                'sort.require' => '排序必须',
            ];
            $all = input('param.');
            $validate = new Validate($rule, $msg);

            if (!$validate->check($all)) {
                $error = $validate->getError();
                return $this->ajaxReturn(1, $error, null);
            }

            $data['type'] = $all['type'];
            $data['pid'] = $all['pid'];
            $data['name'] = $all['name'];
            if ($all['pid'] == 0) {
                $data['level'] = 1;
            } else {
                $data['level'] = 2;
            }
            $data['icon'] = $all['icon'];
            $data['sort'] = $all['sort'];
            $data['status'] = 1;
            $add = Db::name('item_class')->where('id', '=', $id)->update($data);
            if ($add) {
                return $this->ajaxReturn(0, '修改成功', null);
            } else {
                return $this->ajaxReturn(3, '修改失败', null);
            }
        }
    }

    /*
     * 删除项目分类
     * author xfwed 
     * date 2019.09.10
     */

    public function delItemClass() {
        $id = input('param.id');
        $data['status'] = 2;
        $add = Db::name('item_class')->where('id', 'in', $id)->update($data);
        if ($add) {
            return $this->ajaxReturn(0, '删除成功', null);
        } else {
            return $this->ajaxReturn(3, '删除失败', null);
        }
    }

    /*
     * 添加项目
     * author xfwed 
     * date 2019.09.10
     */

    public function addItem() {
        $rule = [
//            'type' => 'require',
            'item_type' => 'require',
            'item_name' => 'require',
            'vice_name' => 'require',
            'item_price' => 'require',
            'special_money' => 'require',
            'item_img' => 'require',
            'people' => 'require',
            'service_time' => 'require',
            'content' => 'require',
            'add_name' => 'require',
        ];
        $msg = [
//            'type.require' => '类型必须',
            'item_type.require' => '标签必须',
            'item_name.require' => '名称必须',
            'vice_name.require' => '副标题必须',
            'item_price.require' => '原价必须',
            'special_money.require' => '特权价必须',
            'item_img.require' => '图片必须',
            'people.require' => '适用人群必须',
            'service_time.require' => '服务时长必须',
            'content.require' => '内容必须',
            'add_name.require' => '添加者必须',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);

        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $store_id = $all['store_id'];
        $store_id = isset($store_id) ? $store_id : 0;
        $itemImg = $all['item_img']; //项目图片
        $itemImg = explode(",", $itemImg);
//        if($all['is_yimei']==1){
//            $type = 1;
//        }  else {
//            $type = input('param.type');//0普通项目 1热玛吉 2美修斯
//        }
        $type = input('param.type');//0普通项目 1热玛吉 2美修斯 3伊丽丝白4华晟澳源 
        if($type == 1 || $type == 3 || $type == 4){
            $is_yimei = 1;
        }  else {
            $is_yimei = 2;
        }
        $sell_place_json = input('param.sell_place_json');
        $sell_place_arr = [];
        if($sell_place_json){
            $sell_place_json = json_decode($sell_place_json,true);
            foreach ($sell_place_json as $k => $v){
                $sell_place_arr[$k] = $v[1];
            }
            $sell_place = implode(',',$sell_place_arr);
        }  else {
            $sell_place = NULL;
        }
        $pay_method = input('param.pay_method');
        $pre_sale = input('param.pre_sale');
        if($pay_method == 1 || $pay_method == 3){
            if($pre_sale <= 0){
                return Utils::ajaxReturn(3, '请输入正确的定金金额', null);
            }
        }
        
        Db::startTrans();
        $data['store_id'] = $store_id;
        $data['type'] = $type;
        $data['item_type'] = $all['item_type'];
        $data['item_name'] = $all['item_name'];
        $data['vice_name'] = $all['vice_name'];
        $data['item_price'] = $all['item_price'];
        $data['special_money'] = $all['special_money'];
        $data['item_img'] = $itemImg[0];
        $data['people'] = $all['people'];
        $data['service_time'] = $all['service_time'];
        $data['content'] = $all['content'];
        $data['is_del'] = 2;
        $data['add_time'] = date('Y-m-d H:i:s');
        $data['add_name'] = $all['add_name'];
        $data['is_yimei'] = $is_yimei;
        $data['activityDesc'] = input('param.activityDesc');
        $data['activityGoodsId'] = input('param.activityGoodsId');
        $data['is_imeigroup'] = $all['is_imeigroup'];
        $data['imeigroup_img'] = $all['imeigroup_img'];
        $data['factory_per'] = input('param.factory_per');
        $data['store_per'] = input('param.store_per');
        $data['staff_per'] = input('param.staff_per');
        $data['kkm_per'] = input('param.kkm_per');
        $data['pay_method'] = input('param.pay_method');
        $data['pre_sale'] = input('param.pre_sale');
        $data['ser_place'] = input('param.ser_place');
        $data['sell_place'] = $sell_place;
        $data['sell_place_json'] = input('param.sell_place_json');
        $insertId = Item::insertGetId($data);
        $imgData = [];
        foreach ($itemImg as $key => $value) {
            $oneData = [
                'item_id' => $insertId,
                'img' => $value,
            ];

            array_push($imgData, $oneData);
        }
        $imgResult = Itemimg::insertAll($imgData);
        
        //生成项目小程序码
        $ApiPath = config('appconfig.ApiPath');
        $postFields['param'] = 'a='.$insertId.'&s=0';
        $postFields['url'] = 'packageA/pages/project/projectDetail/index';
        $relust = Utils::curlPost($ApiPath . '/weChat/getWeChatCodeForUrl/',json_encode($postFields));
        $IndexPath = config('appconfig.IndexPath');
        $relust = json_decode($relust, true)['data'];
        $arr = explode(",", $relust);
        $last = $arr[1];
        $postFields1['img'] = $last;
        $postFields1['modeName'] = 'itemqrcode';
        $relust = Utils::curlPost1($IndexPath.'Public/uploadBase64Img/',$postFields1);
        $relust = json_decode($relust, true)['data'];
        //生成项目sku码
        $sku = Item::itemSku($insertId);
        Item::where('id',$insertId)->update(['xcx_img'=>$relust,'sku'=>$sku]);

        if ($insertId && $imgResult) {
            Db::commit();
            return $this->ajaxReturn(0, '项目添加成功', null);
        } else {
            Db::rollback();
            return $this->ajaxReturn(3, '项目添加失败', null);
        }
    }

    /*
     * 修改项目
     * author xfwed 
     * date 2019.09.10
     */

    public function saveItem() {
        $requestType = input('param.requestType');
        $id = input('param.id');
        if ($requestType == 1) {//1修改前获取信息 2提交修改
            $itemRow = Item::where('id', '=', $id)->find();
            $itemRow['img'] = ItemImg::where('item_id', '=', $id)->select();
            return $this->ajaxReturn(0, '查询成功', $itemRow);
        } else {
            $rule = [
//                'type' => 'require',
                'item_type' => 'require',
                'item_name' => 'require',
                'vice_name' => 'require',
                'item_price' => 'require',
                'special_money' => 'require',
                'item_img' => 'require',
                'people' => 'require',
                'service_time' => 'require',
                'content' => 'require',
            ];
            $msg = [
//                'type.require' => '类型必须',
                'item_type.require' => '标签必须',
                'item_name.require' => '名称必须',
                'vice_name.require' => '副标题必须',
                'item_price.require' => '原价必须',
                'special_money.require' => '特权价必须',
                'item_img.require' => '图片必须',
                'people.require' => '适用人群必须',
                'service_time.require' => '服务时长必须',
                'content.require' => '内容必须',
            ];
            $all = input('param.');
            $validate = new Validate($rule, $msg);

            if (!$validate->check($all)) {
                $error = $validate->getError();
                return $this->ajaxReturn(1, $error, null);
            }
            $store_id = isset($store_id) ? $store_id : 0;
            $itemImg = $all['item_img']; //项目图片
            $itemImg = explode(",", $itemImg);
//            if($all['is_yimei']==1){
//                $type = 1;
//            }  else {
//                $type = input('param.type');//0普通项目 1热玛吉 2美修斯
//            }
            $type = input('param.type');//0普通项目 1热玛吉 2美修斯 3伊丽丝白4华晟澳源 
            if($type == 1 || $type == 3 || $type == 4){
                $is_yimei = 1;
            }  else {
                $is_yimei = 2;
            }
            
            $sell_place_json = input('param.sell_place_json');
            $sell_place_arr = [];
            if($sell_place_json){
                $sell_place_json = json_decode($sell_place_json,true);
                foreach ($sell_place_json as $k => $v){
                    $sell_place_arr[$k] = $v[1];
                }
                $sell_place = implode(',',$sell_place_arr);
            }  else {
                $sell_place = NULL;
            }
            Db::startTrans();
            $data['store_id'] = $store_id;
            $data['type'] = $type;
            $data['item_type'] = $all['item_type'];
            $data['item_name'] = $all['item_name'];
            $data['vice_name'] = $all['vice_name'];
            $data['item_price'] = $all['item_price'];
            $data['special_money'] = $all['special_money'];
            $data['item_img'] = $itemImg[0];
            $data['people'] = $all['people'];
            $data['service_time'] = $all['service_time'];
            $data['content'] = $all['content'];
            $data['add_time'] = date('Y-m-d H:i:s');
            $data['is_yimei'] = $all['is_yimei'];
            $data['activityDesc'] = input('param.activityDesc');
            $data['activityGoodsId'] = input('param.activityGoodsId');
            $data['is_imeigroup'] = $all['is_imeigroup'];
            $data['imeigroup_img'] = $all['imeigroup_img'];
            $data['factory_per'] = input('param.factory_per');
            $data['store_per'] = input('param.store_per');
            $data['staff_per'] = input('param.staff_per');
            $data['kkm_per'] = input('param.kkm_per');
            $data['pay_method'] = input('param.pay_method');
            $data['pre_sale'] = input('param.pre_sale');
            $data['ser_place'] = input('param.ser_place');
            $data['sell_place'] = $sell_place;
            $data['sell_place_json'] = input('param.sell_place_json');
             //生成项目sku码
            $sku = Item::itemSku($id);
            $data['sku'] = $sku;
            $result = Item::where('id', '=', $id)->update($data);
            $imgData = [];
            foreach ($itemImg as $key => $value) {
                $oneData = [
                    'item_id' => $id,
                    'img' => $value,
                ];

                array_push($imgData, $oneData);
            }
            $delResult = Itemimg::where('item_id', '=', $id)->delete();
            $imgResult = Itemimg::insertAll($imgData);

            if ($result && $imgResult) {
                Db::commit();
                return $this->ajaxReturn(0, '项目修改成功', null);
            } else {
                Db::rollback();
                return $this->ajaxReturn(3, '项目修改失败', null);
            }
        }
    }

    /*
     * 项目订单
     * author xfwed 
     * date 2019.09.19
     */

    public function itemOrderList() {
        $status = input('param.status');
        $vip_status = input('param.vip_status');
        $type = input('param.type');
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');
        $searchStr = input('param.search_str');
        $item_name = input('param.item_name');
        $store_type = input('param.store_type');//店铺类型 0全部 1品牌连锁店 2服务授权店	

        $perPage = input('param.perPage');
        $page = input('param.page');

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        $searchStr = trim($searchStr);

        if ($status) {
            $where['o.status'] = $status;
        }
        if($status == -1){
            $where['o.status'] = 0;
        }
        if ($vip_status) {
            $where['c.vip_status'] = $vip_status;
        }
        if ($type) {
            if($type == 1){//普通项目
                $where['o.type'] = $type;
                $where['i.is_special'] = 2;
                $where['i.issue_type'] = 0;
            }elseif ($type == 1.1) {//特色项目
                $where['o.type'] = 1;
                $where['i.is_special'] = 1;
                $where['i.issue_type'] = 0;
            }elseif ($type == 1.2) {//问题项目
                $where['o.type'] = 1;
                $where['i.issue_type'] = ['<>',0];
            }  else {
                $where['o.type'] = $type;
            } 
        }  else {
            $where['o.type'] = ['not in','7,9'];
        }
        if ($end_time && $start_time) {
            $where['o.pay_time'] = array('between', array($start_time, $end_time));
        } elseif (empty($end_time) && $start_time) {
            $time = strtotime($start_time);
            $time2 = $time + 24 * 60 * 60;
            $time2 = date('Y-m-d H:i:s', $time2);
            $where['o.pay_time'] = array('between', array($time, $time2));
        }
        if($item_name && $type==1){
            $where['i.item_name'] = ['like','%'.$item_name.'%'];
        }
        if($store_type){
            $where['s.type'] = $store_type;
        }
        $where = isset($where) ? $where : [];
        if ($searchStr) {
            $orderList = Order::alias('o')
                    ->join('custom c', 'c.id = o.ctm_id', 'left')
                    ->join('store s','s.id = o.store_id','left')
                    ->join('ord_pro op','op.ord_id = o.id','left')
                    ->join('item i','i.id = op.pro_id','left')
                    ->where($where)
                    ->where(function ($query) use ($searchStr) {
                        $query->where('c.custom_name', 'like', '%' . $searchStr . '%')
                        ->whereOr('c.custom_phone', 'like', '%' . $searchStr . '%')
                        ->whereOr('o.ord_num', 'like', '%' . $searchStr . '%');
                    })
                    ->field('o.id,o.ord_num,o.status,o.pay_time,o.type,o.pay_money,o.balance_money,o.red_money,o.special_id,c.custom_name,c.custom_phone,c.vip_status,s.store_name,s.type store_type,op.pro_id')
                    ->order('o.id desc')
                    ->paginate($perPage);
        } else {
            $orderList = Order::alias('o')
                    ->join('custom c', 'c.id = o.ctm_id', 'left')
                    ->join('store s','s.id = o.store_id','left')
                    ->join('ord_pro op','op.ord_id = o.id','left')
                    ->join('item i','i.id = op.pro_id','left')
                    ->where($where)
                    ->field('o.id,o.ord_num,o.status,o.pay_time,o.type,o.pay_money,o.balance_money,o.red_money,o.special_id,c.custom_name,c.custom_phone,c.vip_status,s.store_name,s.type store_type,op.pro_id')
                    ->order('o.id desc')
                    ->paginate($perPage);
        }
        //查询订单购买的项目名称
        foreach ($orderList as $k => $v){
            $type = $v['type'];
            $pro_id = $v['pro_id'];
            //类型 1项目 2超值组合 3充值 4 特权卡5秒杀6体验特权卡7医美项目	
            if($type == 1){
                $item_name = Item::where('id',$pro_id)->value('item_name');
            }elseif ($type == 2) {
                $item_name = Overgroup::where('id',$pro_id)->value('name');
            }elseif ($type == 3) {
                $item_name = '充值';
            }elseif ($type == 4) {
                $item_name = '特权卡';
            }elseif ($type == 5) {
                $miaoshaRow = Miaosha::where('id',$pro_id)->field('name,item_id')->find();
                $item_name = Item::where('id',$miaoshaRow['item_id'])->value('item_name');
                $item_name = $miaoshaRow['name'].'-'.$item_name;
            }elseif ($type == 6) {
                $item_name = '体验特权卡';
            }elseif ($type == 7) {
                $item_name = OrderYimei::alias('y')
                        ->join('item i','i.id = y.item_id','left')
                        ->where('y.ord_id',$v['id'])
                        ->value('i.item_name');
            }
            $orderList[$k]['item_name'] = $item_name;
        }
        //特权卡订单23040，实付金额￥394.05，已返美容金239585.03
        $orderIds = Order::where('pay_status',2)
                ->where('type',4)
                ->column('id');
        $orderCount = count($orderIds);
        $orderMoney = Order::where('pay_status',2)->where('type',4)->sum('pay_money+balance_money');
//        $redPacketCtmIds = Db::name('red_packet_ctm')->where('order_id','in',$orderIds)->column('id');
//        if($redPacketCtmIds){
//            $redMoney = Db::name('redpacket')->where('packet_ctm_id','in',$redPacketCtmIds)->sum('money');
//        }  else {
//            $redMoney = 0;
//        }
        $data['orderCount'] = $orderCount;
        $data['orderMoney'] = $orderMoney;
//        $data['redMoney'] = $redMoney;
        //2021年6月1日前， 特权卡订单23040，实付金额￥394.05
        $orderCount6 = Order::where('pay_status',2)
                ->where('type',4)
                ->where('pay_time','<','2021-06-01')
                ->count();
        $orderMoney6 = Order::where('pay_status',2)
                ->where('type',4)
                ->where('pay_time','<','2021-06-01')
                ->sum('pay_money+balance_money');
        $data['orderCount6'] = $orderCount6;
        $data['orderMoney6'] = $orderMoney6;
        $data['list'] = $orderList;

        return $this->ajaxReturn(0, '查询成功', $data);
    }

    /*
     * 项目订单详情
     * author xfwed 
     * date 2019.09.19
     */

    public function itemOrderInfo() {
        $id = input('param.id');
        $orderRow = Order::alias('o')
                ->join('custom c', 'c.id = o.ctm_id', 'left')
                ->join('coupon p', 'o.cun_id = p.id', 'left')
                ->where('o.id', '=', $id)
                ->field('o.ordtype,o.store_id,o.ord_num,o.status,o.add_time,o.pay_time,o.type,o.pay_money,o.balance_money,o.red_money,o.special_id,c.custom_name,c.custom_phone,c.vip_status,p.money')
                ->find();
        //下单选择的店铺
        if($orderRow['store_id']){
            $orderRow['store_name'] = Store::where('id',$orderRow['store_id'])->value('store_name');
        }
        //项目信息
        $ordpro = OrdPro::where('ord_id', '=', $id)->select();
        foreach ($ordpro as $k => $v) {
            if ($v['type'] == 1 || $v['type'] == 7) {//类型 1项目 2超值组合 3充值 4 特权卡5秒杀	
                $itemdata = Item::where('id', '=', $v['pro_id'])
                        ->field('item_name,item_price,special_money')
                        ->find();
                //查询项目的预约情况
                $yuyueList = YuyueCopy::alias('y')
                        ->join('staff s', 's.id = y.staff_id', 'left')
                        ->join('staff_rank r', 'r.id = s.staff_rank', 'left')
                        ->join('store st', 'st.id = y.store_id', 'left')
                        ->where('y.order_id', '=', $id)
                        ->where('y.item_id', '=', $v['pro_id'])
                        ->order('y.add_time desc')
                        ->field('y.yuyue_id,y.type,y.staff_id,y.store_id,y.status,y.start_time,y.ctmstaff_note,y.confirm_time,y.refused_time,y.refused_why,y.staff_time,y.cancel_time,y.cancel_why,y.add_time,s.staff_name,r.name,st.store_name')
                        ->select();
                $itemdata['yuyuelist'] = $yuyueList;
                $ordpro[$k]['itemdata'] = $itemdata;
            } elseif ($v['type'] == 2) {
                $itemdata = Overgroup::alias('o')
                        ->join('overgroup_item oi', 'oi.overgroup_id = o.id', 'left')
                        ->join('item i', 'i.id = oi.item_id', 'left')
                        ->where('o.id', '=', $v['pro_id'])
                        ->field('i.id,i.item_name,i.item_price,i.special_money')
                        ->select();
                foreach ($itemdata as $key => $val) {
                    //查询项目的预约情况
                    $yuyueList = YuyueCopy::alias('y')
                            ->join('staff s', 's.id = y.staff_id', 'left')
                            ->join('staff_rank r', 'r.id = s.staff_rank', 'left')
                            ->join('store st', 'st.id = y.store_id', 'left')
                            ->where('y.order_id', '=', $id)
                            ->where('y.item_id', '=', $val['id'])
                            ->order('y.add_time desc')
                            ->field('y.yuyue_id,y.type,y.staff_id,y.store_id,y.status,y.start_time,y.ctmstaff_note,y.confirm_time,y.refused_time,y.refused_why,y.staff_time,y.cancel_time,y.cancel_why,y.add_time,s.staff_name,r.name,st.store_name')
                            ->select();
                    $itemdata[$key]['yuyuelist'] = $yuyueList;
                }
                $ordpro[$k]['itemdata'] = $itemdata;
            } elseif ($v['type'] == 3) {
                $itemdata = ['item_name' => '余额充值', 'item_price' => $orderRow['pay_money'], 'special_money' => 0];
                $ordpro[$k]['itemdata'] = $itemdata;
            } elseif ($v['type'] == 4) {
                $itemdata = ['item_name' => '99特权卡', 'item_price' => $orderRow['pay_money'], 'special_money' => 0];
                $ordpro[$k]['itemdata'] = $itemdata;
            } elseif ($v['type'] == 5) {
                $itemdata = Miaosha::alias('m')
                        ->join('item i', 'i.id = m.item_id', 'left')
                        ->where('m.id', '=', $v['pro_id'])
                        ->field('i.id,i.item_name,i.item_price,i.special_money')
                        ->find();
                //查询项目的预约情况
                $yuyueList = YuyueCopy::alias('y')
                        ->join('staff s', 's.id = y.staff_id', 'left')
                        ->join('staff_rank r', 'r.id = s.staff_rank', 'left')
                        ->join('store st', 'st.id = y.store_id', 'left')
                        ->where('y.order_id', '=', $id)
                        ->where('y.item_id', '=', $itemdata['id'])
                        ->order('y.add_time desc')
                        ->field('y.yuyue_id,y.type,y.staff_id,y.store_id,y.status,y.start_time,y.ctmstaff_note,y.confirm_time,y.refused_time,y.refused_why,y.staff_time,y.cancel_time,y.cancel_why,y.add_time,s.staff_name,r.name,st.store_name')
                        ->select();
                $itemdata['yuyuelist'] = $yuyueList;
                $ordpro[$k]['itemdata'] = $itemdata;
            }
        }
        $orderRow['ordpro'] = $ordpro;


        return $this->ajaxReturn(0, '查询成功', $orderRow);
    }

    /*
     * 删除项目
     * author xfwed 
     * date 2019.10.14
     */

    public function delItem() {
        $ids = input('param.ids');
        $is_del = input('param.is_del');
        $save = Item::where('id', 'in', $ids)->update(['is_del' => $is_del]);
        if ($save) {
            return $this->ajaxReturn(0, '操作成功', null);
        } else {
            return $this->ajaxReturn(3, '操作失败', null);
        }
    }

    /*
     * 项目审核
     * author xfwed 
     * date 2019.12.09
     */

    public function auditItem() {
        $id = input('param.id');
        $status = input('param.status');
        $why = input('param.why');
        $audit_name = input('param.audit_name');

        if ($status == 3 && empty($why)) {
            return $this->ajaxReturn(3, '请填写失败原因', null);
        }
        if ($status == 2) {
            $is_del = 1;
            $why = NULL;
        } elseif ($status == 3) {
            $is_del = 2;
        }
        $save = Item::where('id', $id)->update([
            'status' => $status,
            'why' => $why,
            'audit_name' => $audit_name,
            'audit_time' => date('Y-m-d H:i:s', time()),
            'is_del' => $is_del,
        ]);
        if ($save) {
            return $this->ajaxReturn(0, '审核成功', null);
        } else {
            return $this->ajaxReturn(3, '审核失败', null);
        }
    }

    /*
     * 项目退款列表
     * author xfwed 
     * date 2019.12.11
     */

    public function itemRefundList() {
        $admin = new Item();
        $refund_status = input('param.refund_status'); //退款状态
        $ord_num = input('param.ord_num');
        $perPage = input('param.perPage');
        $page = input('param.page');
        $status = input('param.status'); //预约状态
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');
        $phone = input('param.phone');
        $refund_type = input('param.refund_type');//退款类型 1.自动 2.审核
        $store_type = input('param.store_type');//店铺类型 0全部 1品牌连锁店 2服务授权店
        $staff_type = input('param.staff_type');//美容师类型 0全部 1品牌连锁店 2服务授权店

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
//        if ($refund_status) {
//            $where['y.refund_status'] = $refund_status;
//        } else {
//            $where['y.refund_status'] = ['in', '1,2,3'];
//        }
        if($refund_type){
            $where['y.refund_type'] = $refund_type;
        }  
        if ($refund_status) {
            $where['p.status'] = $refund_status;
        } else {
            $where['y.refund_status'] = ['in', '1,2,3'];
        }
        if ($ord_num) {
            $where['o.ord_num'] = $ord_num;
        }
        if ($status) {
            $where['y.status'] = $status;
        }
        if ($phone) {
            $where['c.custom_phone'] = $phone;
        }
        
        if ($end_time && $start_time) {
            $where['p.add_time'] = array('between', array($start_time, $end_time));
        } elseif (empty($end_time) && $start_time) {
            $time = strtotime($start_time);
            $time2 = $time + 24 * 60 * 60;
            $time2 = date('Y-m-d H:i:s', $time2);
            $where['p.add_time'] = array('between', array($time, $time2));
        }
        if($store_type){
            $where['s.type'] = $store_type;
        }
        if($staff_type){
            $where['st.type'] = $staff_type;
        }
        
        //$where['p.status'] = 1;
        $subsql = Db::table('ai_program_refund')
                //->where('id','in',"SELECT MAX('id') FROM ai_program_refund GROUP BY 'yuyue_id'")
                ->where("id in (SELECT MAX(`id`) FROM `ai_program_refund` GROUP BY `yuyue_id`)")
                ->field('id pid,yuyue_id,status,add_time')
                ->buildSql();
        $list = Db::table('ai_yuyue')->alias('y')
                ->join('custom c', 'c.id = y.ctm_id', 'left')
                ->join('item i', 'i.id = y.item_id', 'left')
                ->join('order o', 'o.id = y.order_id', 'left')
                ->join('store s', 's.id = y.store_id', 'left')
                ->join('staff st', 'st.id = y.staff_id', 'left')
                ->join([$subsql => 'p'],'p.yuyue_id=y.id','left')
                ->where($where)
                ->group('y.id')
                ->order('p.add_time asc,p.pid asc')
                ->field('y.id,y.status,y.money,y.refund_status,y.refund_type,c.custom_name,c.custom_phone,c.vip_status,i.item_name,o.ord_num,s.store_name,s.type store_type,st.staff_name,st.type staff_type,p.add_time,p.status pstatus')
                ->paginate($perPage);
//        print_r(Yuyue::getLastSql());
        return $this->ajaxReturn(0, '查询成功', $list);
    }
    
    /*
     * 项目售后详情
     * author xfwed 
     * date 2019.12.13
     */

    public function itemRefundInfo() {
        $id = input('param.id');
        //$where['p.status'] = 1;
        $where['y.id'] = $id;
        $subsql = Db::table('ai_program_refund')
                //->where('id','in',"SELECT MAX('id') FROM ai_program_refund GROUP BY 'yuyue_id'")
                ->where("id in (SELECT MAX(`id`) FROM `ai_program_refund` GROUP BY `yuyue_id`)")
                ->field('yuyue_id,status,add_time')
                ->buildSql();
        $Row = Yuyue::alias('y')
                ->join('custom c', 'c.id = y.ctm_id', 'left')
                ->join('item i', 'i.id = y.item_id', 'left')
                ->join('order o', 'o.id = y.order_id', 'left')
                ->join('store s', 's.id = y.store_id', 'left')
                ->join('staff st', 'st.id = y.staff_id', 'left')
                //->join('program_refund p','p.yuyue_id=y.id','left')
                ->join([$subsql => 'p'],'p.yuyue_id=y.id','left')
                ->where($where)
//                ->field('y.id,y.status,y.money,y.refund_status,y.staff_time,c.custom_name,c.custom_phone,c.vip_status,i.item_name,i.item_price,i.special_money,o.ord_num,o.pay_time,o.ordtype,o.pay_money,o.red_money,o.balance_money,s.store_name,st.staff_name,p.add_time,p.apply_reason,p.refund_note,p.certificate_photo')
                ->field('y.id,y.status,y.money,y.refund_status,y.staff_time,c.custom_name,c.custom_phone,c.vip_status,i.item_name,i.item_price,i.special_money,o.ord_num,o.pay_time,o.ordtype,o.pay_money,o.red_money,o.balance_money,s.store_name,st.staff_name,p.add_time,p.status pstatus')
                ->find();
        $refundList = ProgramRefund::where('yuyue_id',$id)->order('id asc')->select();
        foreach ($refundList as $k => $v){
            $certificate_photo = substr($v['certificate_photo'],0, -1);
            $refundList[$k]['certificate_photo'] = explode(",", $certificate_photo);
        }
        $Row['refundList'] = $refundList;
        //查询短信记录
        $smsList = Db::name('sms')->where('order_id',$id)->select();
        $Row['smsList'] = $smsList;
        return $this->ajaxReturn(0, '查询成功', $Row);
    }

    /*
     * 项目退款审核(最后一步财务审核)
     * author xfwed
     * date 2019-12-11 
     */

    public function auditItemRefund() {
        $yuyue_id = input('param.yuyue_id');
        $refund_status = input('param.refund_status'); //2成功3失败
        $why = input('param.why'); //失败的原因
        if ($refund_status == 3 && empty($why)) {
            return $this->ajaxReturn(3, '请输入拒绝原因', null);
        }
        $ApiPath = config('appconfig.ApiPath');
        if ($refund_status == 2) {
            $result = Utils::curlPost1($ApiPath . 'order/programRefund/' . $yuyue_id);
        } elseif ($refund_status == 3) {
            $data['yuyueId'] = $yuyue_id;
            $data['refuseReason'] = $why;
            $result = Utils::curlPost($ApiPath . 'order/refuseApplyRefund/', json_encode($data));
        }
        $result = json_decode($result,TRUE);
        if ($result['code'] == 0) {
            return $this->ajaxReturn(0, '审核成功', null);
        } else {
            return $this->ajaxReturn(3, '审核失败', null);
        }
    }
    /*
     * 项目退款审核(客服审核)
     * author xfwed
     * date 2020-08-06 
     */

    public function callAuditItemRefund() {
        $yuyue_id = input('param.yuyue_id');
        $refund_status = input('param.refund_status'); //3失败6客服通过
        $why = input('param.why'); //失败的原因
        $callnote = input('param.callnote');//客服沟通备注  refund_status = 6的时候必选
        if ($refund_status == 3 && empty($why)) {
            return $this->ajaxReturn(3, '请输入拒绝原因', null);
        }
        if ($refund_status == 6 && empty($callnote)) {
            return $this->ajaxReturn(3, '请输入沟通备注', null);
        }
        $ApiPath = config('appconfig.ApiPath');
        if ($refund_status == 3) {
            $data['yuyueId'] = $yuyue_id;
            $data['refuseReason'] = $why;
            $result = Utils::curlPost($ApiPath . 'order/refuseApplyRefund/', json_encode($data));
        }elseif ($refund_status == 6) {
            $row = ProgramRefund::where('yuyue_id',$yuyue_id)->order('id desc')->field('id,add_time',true)->find();
            if($row['status'] != 5){
                return $this->ajaxReturn(3, '请等待老板通过后操作', null);
            }
            $row['add_time'] = date('Y-m-d H:i:s');
            $row['callnote'] = $callnote;
            $row['status'] = 6;
            $result6 = ProgramRefund::insert($row->toArray());
            if($result6){
                return $this->ajaxReturn(0, '审核成功', null);
            }  else {
                 return $this->ajaxReturn(3, '审核失败', null);
            }
        }
        $result = json_decode($result,TRUE);
        if ($result['code'] == 0) {
            return $this->ajaxReturn(0, '审核成功', null);
        } else {
            return $this->ajaxReturn(3, '审核失败', null);
        }
    }
    
    /*
     * 项目退款审核(经理审核)
     * author xfwed
     * date 2020-08-06 
     */

    public function managerAuditItemRefund() {
        $yuyue_id = input('param.yuyue_id');
        $refund_status = input('param.refund_status'); //3失败7经理通过
        $why = input('param.why'); //失败的原因
        if ($refund_status == 3 && empty($why)) {
            return $this->ajaxReturn(3, '请输入拒绝原因', null);
        }
       
        $ApiPath = config('appconfig.ApiPath');
        if ($refund_status == 3) {
            $data['yuyueId'] = $yuyue_id;
            $data['refuseReason'] = $why;
            $result = Utils::curlPost($ApiPath . 'order/refuseApplyRefund/', json_encode($data));
        }elseif ($refund_status == 7) {
            $row = ProgramRefund::where('yuyue_id',$yuyue_id)->order('id desc')->field('id,add_time',true)->find();
            if($row['status'] != 6){
                return $this->ajaxReturn(3, '请等待客服通过后操作', null);
            }
            $row['add_time'] = date('Y-m-d H:i:s');
            $row['status'] = 7;
            $result6 = ProgramRefund::insert($row->toArray());
            if($result6){
                return $this->ajaxReturn(0, '审核成功', null);
            }  else {
                 return $this->ajaxReturn(3, '审核失败', null);
            }
        }
        $result = json_decode($result,TRUE);
        if ($result['code'] == 0) {
            return $this->ajaxReturn(0, '审核成功', null);
        } else {
            return $this->ajaxReturn(3, '审核失败', null);
        }
    }
    
    /*
     * 项目退款重审
     * author xfwed
     * date 2020-09-16 
     * 被拒绝的单后台有权限重新审核
     */

    public function againAudit() {
        $yuyue_id = input('param.yuyue_id');
        //预约表修改为申请中  copy表复制一条数据  新增记录
        Db::startTrans(); //开启事务
        $yuyueSave =  Yuyue::where('id',$yuyue_id)->update(['refund_status'=>1]);
        $yuyueRow = YuyueCopy::where('yuyue_id',$yuyue_id)->field('id',true)->find();
        $yuyueRow['refund_status'] = 1;
        $yuyueRow['add_time'] = date('Y-m-d H:i:s');
        $yuyuecopySave = YuyueCopy::insert($yuyueRow->toArray());
        
        $row = ProgramRefund::where('yuyue_id',$yuyue_id)
                ->order('id desc')
                ->field('id,add_time,refuse_reason',true)
                ->find();
        if($row['status'] != 4){
                return $this->ajaxReturn(3, '该订单不需要重新审核', null);
        }
        
        $row['add_time'] = date('Y-m-d H:i:s');
        $row['status'] = 6;
        $ProgramRefundSave = ProgramRefund::insert($row->toArray());
      
        if ($yuyueSave && $yuyuecopySave && $ProgramRefundSave) {
            Db::commit();
            return $this->ajaxReturn(0, '审核成功', null);
        } else {
            Db::rollback(); //事务回滚
            return $this->ajaxReturn(3, '审核失败', null);
        }
    }


    /*
     * 项目关联商品
     * author xfwed
     * date 2019-12-12
     */

    public function itemToGoods() {
        $item_id = input('param.item_id');
        $goods_ids = input('param.goods_ids');
        ItemToGoods::where('item_id', $item_id)->delete();
        $goods_ids = explode(",", $goods_ids);
        foreach ($goods_ids as $k => $v) {
            ItemToGoods::insert(['item_id' => $item_id, 'goods_info_id' => $v]);
        }
        return $this->ajaxReturn(0, '绑定成功', null);
    }
    
    /*
     * 设置/取消今日上新
     * author xfwed
     * date 2020-04-29
     */

    public function setOrCallOffDayNew() {
        $item_id = input('param.item_id');
        $is_new = input('param.is_new');
        $row = Item::where('id',$item_id)->update(['is_new'=>$is_new]);
        if($row){
            return $this->ajaxReturn(0, '操作成功', null);
        }  else {
            return $this->ajaxReturn(3, '操作失败', null);
        }
    }
    
    /*
     * 预约列表
     * author xfwed 
     * date 2020.06.16
     */

    public function yuyueList() {
        $admin = new Item();
        $staff_name = input('param.staff_name');
        $ctm_name = input('param.ctm_name');
        $ctm_phone = input('param.ctm_phone');
        $store_name = input('param.store_name');
        $order_num = input('param.order_num');
        $perPage = input('param.perPage');
        $page = input('param.page');
        $status = input('param.status');
        $store_type = input('param.store_type');//店铺类型 0全部 1品牌连锁店 2服务授权店	
        $staff_type = input('param.staff_type');//美容师类型 0全部 1品牌连锁店 2服务授权店

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        if ($staff_name) {
            $where['s.staff_name'] = ['like', '%' . $staff_name . '%'];
        }
        if ($ctm_name) {
            $where['c.custom_name'] = ['like', '%' . $ctm_name . '%'];
        }
        if ($ctm_phone) {
            $where['c.custom_phone'] = $ctm_phone;
        }
        if ($store_name) {
            $where['st.store_name'] = ['like', '%' . $store_name . '%'];
        }
        if ($order_num) {
            $where['o.ord_num'] = $order_num;
        }

        if ($status) {//1待预约2待接单3待服务4已完成5拒绝接单6已退款7已评价8已回复9用户取消10美容师取消11派单中12预约超时 13.服务中(暂未启用)
            if($status == 2){
                $where['y.user_confirm_time'] = ['>',date('Y-m-d H:i:s',time()-300)];
                $where['y.status'] = 2;
            }elseif ($status == 25) {
                $where['y.user_confirm_time'] = ['<',date('Y-m-d H:i:s',time()-300)];
                $where['y.status'] = 2;
            }  else {
                $where['y.status'] = $status;
            }
        }
        if($store_type){
            $where['st.type'] = $store_type;
        }

        if($staff_type){
            $where['s.type'] = $staff_type;
        }

//        $where['i.is_del'] = 1;
        $where = isset($where) ? $where : [];
        
        $yuyuList = Yuyue::alias('y')
                ->join('staff s','s.id = y.staff_id','left')
                ->join('custom c','c.id = y.ctm_id','left')
                ->join('store st','st.id = y.store_id','left')
                ->join('order o','o.id = y.order_id','left')
                ->join('item i','i.id = y.item_id','left')
                ->field('y.*,s.staff_name,s.type staff_type,c.custom_name,st.store_name,st.type store_type,o.ord_num,i.item_name,s.telephone')
                ->where($where)
                ->order('y.id desc')
                ->paginate($perPage);
        
        return $this->ajaxReturn(0, '查询成功', $yuyuList);
    }
    
    /*
     * 项目销量图表
     * author xfwed 
     * date 2020.07.02
     */

    public function itemSellCount() {
        $list = Item::where('is_del',1)
                ->where('status',2)
                ->where('sell_count','<>',0)
                ->order('sell_count desc')
                ->limit('0,30')
                ->field('id,item_name,sell_count')
                ->select();
        
        return $this->ajaxReturn(0, '查询成功', $list);
    }
    
    /*
     * 添加项目服务流程
     * author xfwed 
     * date 2020.07.07
     */

    public function addItemSerProcess() {
        $rule = [
            'item_id' => 'require',
            'sort' => 'require',
            'name' => 'require',
            'minute' => 'require',
            'facility' => 'require',
            'good_id' => 'require',
            'content' => 'require',
//            'img' => 'require',
        ];
        $msg = [
            'item_id.require' => '项目id必须',
            'sort.require' => '排序必须',
            'name.require' => '流程名称必须',
            'minute.require' => '建议时长必须',
            'facility.require' => '所需设备必须',
            'good_id.require' => '商品id必须',
            'content.require' => '内容必须',
//            'img.require' => '图片必须',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);

        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $item_id = $all['item_id'];
        $sort = $all['sort']; 
        $name = $all['name']; 
        $minute = $all['minute']; 
        $facility = $all['facility']; 
        $good_id = $all['good_id']; 
        $content = $all['content']; 
        $img = input('param.img');
        $facility_img = input('param.facility_img');//所需设备图片
//        $process = [
//            ['sort'=>1,'name'=>'流程1','minute'=>5,'facility'=>'洁面仪','good_id'=>2,'content'=>'辅导费','img'=>''],
//            ['sort'=>2,'name'=>'流程2','minute'=>5,'facility'=>'散光仪','good_id'=>3,'content'=>'辅导费','img'=>''],
//            ];
        $row = ItemProcess::where('item_id',$item_id)->where('is_del',2)->where('sort',$sort)->find();
        if($row){
            return $this->ajaxReturn(3, '该项目此流程已经添加', null);
        }

        $detail_arr = [
            'item_id' => $item_id,
            'sort' => $sort,
            'name' => $name,
            'minute' => $minute,
            'facility' => $facility,
            'facility_img' => $facility_img,
            'good_id' => $good_id,
            'content' => $content,
            'img' => $img,
            'add_time' => date('Y-m-d H:i:s'),
        ];
        
        $itemProcessResult = ItemProcess::insert($detail_arr);
        
        //将服务流程里面绑定的商品添加到项目绑定的商品里面
        $find = ItemToGoods::where('item_id',$item_id)->where('goods_info_id',$good_id)->find();
        if(empty($find)){
            ItemToGoods::insert(['item_id' => $item_id, 'goods_info_id' => $good_id]);
        }
        
        if ($itemProcessResult) {
            return $this->ajaxReturn(0, '添加成功', null);
        } else {
            return $this->ajaxReturn(3, '添加失败', null);
        }
    }
    
    /*
     * 修改项目服务流程
     * author xfwed 
     * date 2020.07.07
     */

    public function saveItemSerProcess() {
            $rule = [
                'id' => 'require',
                'item_id' => 'require',
                'sort' => 'require',
                'name' => 'require',
                'minute' => 'require',
                'facility' => 'require',
                'good_id' => 'require',
                'content' => 'require',
//                'img' => 'require',
            ];
            $msg = [
                'id.require' => '编号必须',
                'item_id.require' => '项目编号必须',
                'sort.require' => '排序必须',
                'name.require' => '名称必须',
                'minute.require' => '建议时长必须',
                'facility.require' => '所需设备',
                'good_id.require' => '商品id必须',
                'content.require' => '流程简介必须',
//                'img.require' => '图片必须',
            ];
            $all = input('param.');
            $validate = new Validate($rule, $msg);

            if (!$validate->check($all)) {
                $error = $validate->getError();
                return $this->ajaxReturn(1, $error, null);
            }
            $oldGoodId = ItemProcess::where('id',$all['id'])->value('good_id');
            
            $detail['item_id'] = $all['item_id'];
            $detail['sort'] = $all['sort'];
            $detail['name'] = $all['name'];
            $detail['minute'] = $all['minute'];
            $detail['facility'] = $all['facility'];
            $detail['facility_img'] = $all['facility_img'];
            $detail['good_id'] = $all['good_id'];
            $detail['content'] = $all['content'];
            $detail['img'] = input('param.img');
            $detail['add_time'] = date('Y-m-d H:i:s');

            $itemProcessResult = ItemProcess::where('id',$all['id'])
                    ->update($detail);
            
            //将服务流程里面绑定的商品添加到项目绑定的商品里面
            ItemToGoods::where('item_id',$all['item_id'])->where('goods_info_id',$oldGoodId)->delete();
            $find = ItemToGoods::where('item_id',$all['item_id'])->where('goods_info_id',$all['good_id'])->find();
            if(empty($find)){
                ItemToGoods::insert(['item_id' => $all['item_id'], 'goods_info_id' => $all['good_id']]);
            }

            if ($itemProcessResult) {
                return $this->ajaxReturn(0, '修改成功', null);
            } else {
                return $this->ajaxReturn(3, '修改失败', null);
            }
        
    }
    
    /*
     * 删除项目服务流程
     * author xfwed 
     * date 2020.07.07
     */

    public function delItemSerProcess() {
            $rule = [
                'id' => 'require',
            ];
            $msg = [
                'id.require' => '编号必须',
            ];
            $all = input('param.');
            $validate = new Validate($rule, $msg);

            if (!$validate->check($all)) {
                $error = $validate->getError();
                return $this->ajaxReturn(1, $error, null);
            }
            $find = ItemProcess::where('id',$all['id'])->find();
            
            $detail['is_del'] = 1;
            
            $itemProcessResult = ItemProcess::where('id',$all['id'])
                    ->update($detail);
            
            //将服务流程里面绑定的商品添加到项目绑定的商品里面
            ItemToGoods::where('item_id',$find['item_id'])->where('goods_info_id',$find['good_id'])->delete();
            
            if ($itemProcessResult) {
                return $this->ajaxReturn(0, '删除成功', null);
            } else {
                return $this->ajaxReturn(3, '删除失败', null);
            }
        
    }
    
    /*
     * 查看项目服务流程
     * author xfwed 
     * date 2020.07.07
     */

    public function findItemSerProcess() {
            $rule = [
                'item_id' => 'require',
            ];
            $msg = [
                'item_id.require' => '编号必须',
            ];
            $all = input('param.');
            $validate = new Validate($rule, $msg);

            if (!$validate->check($all)) {
                $error = $validate->getError();
                return $this->ajaxReturn(1, $error, null);
            }
            $detail['is_del'] = 1;
            
            $itemProcessResult = ItemProcess::where('item_id',$all['item_id'])
                    ->where('is_del',2)
                    ->order('sort asc')
                    ->select();

            if ($itemProcessResult) {
                return $this->ajaxReturn(0, '查询成功', $itemProcessResult);
            } else {
                return $this->ajaxReturn(0, '查询失败', []);
            }
        
    }
    
    /*
     * 审核项目退款发送短信
     * 作者 xfwed
     * 日期 2020-08-31
     */

    public function sendSms() {
        $rule = [
            'phone' => 'require|length:11',
            'order_id' => 'require',
            'content' => 'require',
        ];
        $msg = [
            'phone.require' => '手机号必须',
            'phone.length' => '手机号长度为11',
            'order_id.require' => '订单id必须',
            'content.require' => '短信必填',
        ];
        $all = input('post.');
        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $telephone = $all['phone'];
        $order_id = $all['order_id'];
        $staffRow = Custom::where('custom_phone', '=', $telephone)
                //->where('staff_on', '=', Staff::STAFF_ON_1)
                ->find();
        if (is_null($staffRow)) {
            return $this->ajaxReturn(3, '手机号未注册', null);
        }

        $content = $all['content'];
        $sendResult = Utils::sendSms($telephone, $content);
        if ($sendResult['code'] == 'success') {
            //写入短信内容
            $codeData = [
                'type' => 1,
                'phone' => $telephone,
                'order_id' => $order_id,
                'content' => $content,
                'add_time' => date('Y-m-d H:i:s'),
            ];
            Db::name('sms')->insert($codeData);
            return $this->ajaxReturn(0, '短信发送成功', null);
        } else {
            return $this->ajaxReturn(3, $sendResult['msg'], null);
        }
    }
    
    /*
     * 丽人订单列表
     * author xfwed 
     * date 2020.10.21
     * 
     * @param int perPage 每页数量 非必须，默认20
     * @param int page 当前页数 非必须，默认0
     */

    public function yimeiOrderList() {
        $rule = [
            'perPage' => 'integer|egt:1',
            'page' => 'integer|egt:0',
        ];
        $msg = [
            'perPage.require' => '每页条数必须',
            'page.require' => '页数必须',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }

        $type = input('param.type');//0全部1待付款11待付尾款2待服务3已完成4已取消
        $item_type = input('param.item_type');//0全部 1热玛吉3伊丽丝白4华晟澳源
        $ctm_phone = input('param.phone');
        $store_name = input('param.store_name');
        $perPage = isset($all['perPage']) ? $all['perPage'] : 20;
        $page = isset($all['page']) ? $all['page'] : 0;
        if ($page == 0) {
            $page = 1;
        }
       
        if($type == 1){
            $where['oy.type'] = ['in','0,1'];
            $where['oy.status'] = ['in','0,2'];
            $where['o.status'] = 1;
        }elseif ($type == 11) {
//            $where['oy.type'] = 2;
//            $where['oy.status'] = ['in','0,2'];
//            
//            $where1['oy.type'] = 1;
//            $where1['oy.status'] = 1;
            $a = " (oy.type=2 and oy.status in (0,2)) or (oy.type =1 and oy.status=1)";
            $where['o.status'] = 1;
        }elseif ($type == 2) {
            $where['o.status'] = 2;
            $where['o.yimei_status'] = 0;
        }elseif ($type == 3) {
            $where['o.status'] = 2;
            $where['o.yimei_status'] = 1;
        }elseif ($type == 4) {
            $where['o.status'] = 0;
        }
        
        if($ctm_phone){
            $where['c.custom_phone'] = $ctm_phone;
        }

        if($store_name){
            $where['s.store_name'] = ['like','%'.$store_name.'%'];
        }
        if($item_type){
            $where['i.type'] = $item_type;
        }
        $where['o.type'] = 7;
        $a = isset($a)?$a:'';
        //100待付全款 110待付定金 120待付尾款 20待服务 21已完成
        $list = Order::alias('o')
                ->join("(SELECT * FROM ai_order_yimei WHERE id IN (SELECT MAX(id) FROM ai_order_yimei GROUP by ord_id)) oy",'oy.ord_id = o.id','left')
                ->join('item i','i.id = oy.item_id','left')
                ->join('custom c','c.id = o.ctm_id','left')
                ->join('store s','s.id = o.store_id','left')
                ->where($where)
                ->where($a)
                ->order('oy.pay_time desc,o.add_time desc,o.id desc')
                ->group('o.id')
                ->field('o.id,o.ord_num,o.status,o.pay_money,o.balance_money,o.yimei_status,o.paid_money,o.add_time,oy.pay_time,i.id item_id,i.item_name,i.item_img,c.custom_name,c.custom_phone,s.store_name')
                ->paginate($perPage)
                ->each(function($item,$key){
                    $status = $item['status'];
                    $order_id = $item['id'];
                    if($status == 1){
                        $orderyimeiRow = OrderYimei::where('ord_id',$order_id)
                                ->order('id desc')
                                ->field('id,type,status,pay_money')
                                ->find();
                        if($orderyimeiRow['type']==0){
                            if($orderyimeiRow['status'] == 0 || $orderyimeiRow['status'] == 2){
                                $item['status'] = 100; //待付全款
                            }
                        }elseif ($orderyimeiRow['type']==1) {
                            if($orderyimeiRow['status'] == 0 || $orderyimeiRow['status'] == 2){
                                $item['status'] = 110; //待付定金
                                $item['pay_money'] = $orderyimeiRow['pay_money'];
                            }  else {
                                $item['status'] = 120; //待付尾款
                                $item['pay_money'] = $item['pay_money']-$item['paid_money'];
                            }
                        }elseif ($orderyimeiRow['type']==2) {
                            if($orderyimeiRow['status'] == 0 || $orderyimeiRow['status'] == 2){
                                $item['status'] = 120; //待付尾款
                                $item['pay_money'] = $item['pay_money']-$item['paid_money'];
                            }
                        }
                    }elseif ($status == 2) {
                        if($item['yimei_status'] == 0){
                            $item['status'] = 20;//待服务
                        }  else {
                            $item['status'] = 21;//已完成
                        }
                    }
                    return $item;
                });
        return $this->ajaxReturn(0, '查询成功', $list);
    }
    
    /*
     * 丽人订单详情
     * author xfwed 
     * date 2020.10.21
     * 
     * @param int perPage 每页数量 非必须，默认20
     * @param int page 当前页数 非必须，默认0
     */

    public function yimeiOrderInfo() {
        $rule = [
            'ord_id' => 'require',
        ];
        $msg = [
            'ord_id.require' => '订单id必须',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }

        $ord_id = $all['ord_id'];

        $where['o.type'] = 7;
        $where['o.id'] = $ord_id;
        //100待付全款 110待付定金 120待付尾款 20待服务 21已完成
        $orderRow = Order::alias('o')
                ->join("(SELECT * FROM ai_order_yimei WHERE id IN (SELECT MAX(id) FROM ai_order_yimei GROUP by ord_id)) oy",'oy.ord_id = o.id','left')
                ->join('item i','i.id = oy.item_id','left')
                ->join('store s','s.id = o.store_id','left')
                ->join('custom c','c.id = o.ctm_id','left')
                ->where($where)
                ->order('o.id desc')
                ->group('o.id')
                ->field('o.id,o.ord_num,o.status,o.pay_money,o.balance_money,o.yimei_status,o.paid_money,o.yimei_code,i.id item_id,i.item_name,i.item_img,s.store_name,c.custom_name,c.custom_phone')
                ->find();
        $status = $orderRow['status'];
//        $orderRow['pay_money'] = $orderRow['pay_money'] - $orderRow['paid_money'];
        if($status == 1){
            $orderyimeiRow = OrderYimei::where('ord_id',$ord_id)
                    ->order('id desc')
                    ->field('id,type,status,pay_money')
                    ->find();
            if($orderyimeiRow['type']==0){
                if($orderyimeiRow['status'] == 0 || $orderyimeiRow['status'] == 2){
                    $orderRow['status'] = 100; //待付全款
                }
            }elseif ($orderyimeiRow['type']==1) {
                if($orderyimeiRow['status'] == 0 || $orderyimeiRow['status'] == 2){
                    $orderRow['status'] = 110; //待付定金
                }  else {
                    $orderRow['status'] = 120; //待付尾款
                }
            }elseif ($orderyimeiRow['type']==2) {
                if($orderyimeiRow['status'] == 0 || $orderyimeiRow['status'] == 2){
                    $orderRow['status'] = 120; //待付尾款
                }
            }
        }elseif ($status == 2) {
            if($orderRow['yimei_status'] == 0){
                $orderRow['status'] = 20;//待服务
            }  else {
                $orderRow['status'] = 21;//已完成
            }
        }
        $orderyimeilist = OrderYimei::where('ord_id',$ord_id)
                    ->where('status',1)
                    ->order('id asc')
                    ->field('id,type,status,pay_money,ord_num,add_time')
                    ->select();
        $orderRow['orderyimeilist'] = $orderyimeilist;
                
        return Utils::ajaxReturn(0, '查询成功', $orderRow);
    }
    
    /*
     * 添加i美套餐项目
     * author xfwed 
     * date 2020.11.11
     */

    public function addimeigroup() {
        $rule = [
            'item_id' => 'require',
            'sort' => 'require',
            'name' => 'require',
            'content' => 'require',
            'img' => 'require',
        ];
        $msg = [
            'item_id.require' => '项目id必须',
            'sort.require' => '排序必须',
            'name.require' => '流程名称必须',
            'content.require' => '内容必须',
            'img.require' => '图片必须',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);

        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $item_id = $all['item_id'];
        $sort = $all['sort']; 
        $name = $all['name']; 
        $content = $all['content']; 
        $img = $all['img']; 
        $itemRow = Item::where('id',$item_id)->find();
        if(empty($itemRow)){
            return $this->ajaxReturn(3, '该项目不存在', null);
        }
        if($itemRow['is_imeigroup'] == 2){
            return $this->ajaxReturn(3, '该项目不是i美套餐项目', null);
        }
        $row = Imeigroup::where('item_id',$item_id)->where('is_del',2)->where('sort',$sort)->find();
        if($row){
            return $this->ajaxReturn(3, '该项目已经添加', null);
        }

        $detail_arr = [
            'item_id' => $item_id,
            'sort' => $sort,
            'name' => $name,
            'content' => $content,
            'img' => $img,
            'add_time' => date('Y-m-d H:i:s'),
        ];
        
        $itemResult = Imeigroup::insert($detail_arr);
        
        if ($itemResult) {
            return $this->ajaxReturn(0, '添加成功', null);
        } else {
            return $this->ajaxReturn(3, '添加失败', null);
        }
    }
    
    /*
     * 修改i美套餐项目
     * author xfwed 
     * date 2020.11.11
     */

    public function saveimeigroup() {
            $rule = [
                'id' => 'require',
                'item_id' => 'require',
                'sort' => 'require',
                'name' => 'require',
                'content' => 'require',
                'img' => 'require',
            ];
            $msg = [
                'id.require' => '编号必须',
                'item_id.require' => '项目id必须',
                'sort.require' => '排序必须',
                'name.require' => '流程名称必须',
                'content.require' => '内容必须',
                'img.require' => '图片必须',
            ];
            $all = input('param.');
            $validate = new Validate($rule, $msg);

            if (!$validate->check($all)) {
                $error = $validate->getError();
                return $this->ajaxReturn(1, $error, null);
            }
            
            $detail['item_id'] = $all['item_id'];
            $detail['sort'] = $all['sort'];
            $detail['name'] = $all['name'];
            $detail['content'] = $all['content'];
            $detail['img'] = $all['img'];
            $detail['add_time'] = date('Y-m-d H:i:s');

            $itemProcessResult = Imeigroup::where('id',$all['id'])
                    ->update($detail);
            if ($itemProcessResult) {
                return $this->ajaxReturn(0, '修改成功', null);
            } else {
                return $this->ajaxReturn(3, '修改失败', null);
            }
        
    }
    
    /*
     * 删除i美套餐项目
     * author xfwed 
     * date 2020.11.11
     */

    public function delimeigroup() {
            $rule = [
                'id' => 'require',
            ];
            $msg = [
                'id.require' => '编号必须',
            ];
            $all = input('param.');
            $validate = new Validate($rule, $msg);

            if (!$validate->check($all)) {
                $error = $validate->getError();
                return $this->ajaxReturn(1, $error, null);
            }
            $detail['is_del'] = 1;
            
            $itemProcessResult = Imeigroup::where('id',$all['id'])
                    ->update($detail);
            
            if ($itemProcessResult) {
                return $this->ajaxReturn(0, '删除成功', null);
            } else {
                return $this->ajaxReturn(3, '删除失败', null);
            }
        
    }
    
    /*
     * 查看i美套餐项目
     * author xfwed 
     * date 2020.11.11
     */

    public function findimeigroup() {
            $rule = [
                'item_id' => 'require',
            ];
            $msg = [
                'item_id.require' => '编号必须',
            ];
            $all = input('param.');
            $validate = new Validate($rule, $msg);

            if (!$validate->check($all)) {
                $error = $validate->getError();
                return $this->ajaxReturn(1, $error, null);
            }
            
            $itemProcessResult = Imeigroup::where('item_id',$all['item_id'])
                    ->field('id,sort,name,img,content')
                    ->where('is_del',2)
                    ->order('sort asc')
                    ->select();

            if ($itemProcessResult) {
                return $this->ajaxReturn(0, '查询成功', $itemProcessResult);
            } else {
                return $this->ajaxReturn(0, '查询失败', []);
            }
        
    }
    
    /*
     * 项目最优组合列表
     * author xfwed 
     * date 2020.12.09
     * 
     * @param int perPage 每页数量 非必须，默认20
     * @param int page 当前页数 非必须，默认0
     */

    public function itemBestGroupList() {
        $rule = [
            'item_id' => 'require',
        ];
        $msg = [
            'item_id.require' => '编号必须',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return Utils::ajaxReturn(1, $error, null);
        }

        $item_id = input('param.item_id');//项目id
       
        $ids = Item::where('id',$item_id)->value('bestgroup_itemids');
        $list = Item::where('id','in',$ids)
                ->where('status',2)
                ->where('is_del',1)
                ->field('id,item_name,item_price,special_money,item_img,add_time')
                ->select();
        return $this->ajaxReturn(0, '查询成功', $list);
    }
    
    /*
     * 更新项目最优组合
     * author xfwed 
     * date 2020.12.09
     * 
     * @param int perPage 每页数量 非必须，默认20
     * @param int page 当前页数 非必须，默认0
     */

    public function saveItemBestGroup() {
        $rule = [
            'item_id' => 'require',
            //'bestgroup_itemids' => 'require',
        ];
        $msg = [
            'item_id.require' => '编号必须',
            //'bestgroup_itemids.require' => '组合编号必须',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return Utils::ajaxReturn(1, $error, null);
        }

        $item_id = input('param.item_id');//项目id
        $bestgroup_itemids = input('param.bestgroup_itemids');//组合编号;
       
        $list = Item::where('id',$item_id)
                ->update(['bestgroup_itemids'=>$bestgroup_itemids]);
        return $this->ajaxReturn(0, '更新成功', null);
    }
    
    /* 导出项目订单
     * author xfwed
     * date 2021-01-06
     */

    public function itemOrderListExcel() {
        $status = input('param.status');
        $vip_status = input('param.vip_status');
        $type = input('param.type');
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');
        $searchStr = input('param.search_str');
        $item_name = input('param.item_name');
        $searchStr = trim($searchStr);
        $store_id = input('param.store_id');
        $agency_id = input('param.agency_id'); //代理id
        $store_ids = Store::where('agency_id',$agency_id)->column('id');
        $store_ids = implode(',', $store_ids);
        
        if($store_id){
            $where['s.id'] = $store_id;
        }  else {
            if($agency_id){
                $where['s.id'] = ['in',$store_ids];
            }
        }

        if ($status) {
            $where['o.status'] = $status;
        }
        if($status == -1){
            $where['o.status'] = 0;
        }
        if ($vip_status) {
            $where['c.vip_status'] = $vip_status;
        }
        if ($type) {
            $where['o.type'] = $type;
        }  else {
            $where['o.type'] = ['<>',7];
        }
        if ($end_time && $start_time) {
            $where['o.pay_time'] = array('between', array($start_time, $end_time));
        } elseif (empty($end_time) && $start_time) {
            $time = strtotime($start_time);
            $time2 = $time + 24 * 60 * 60;
            $time2 = date('Y-m-d H:i:s', $time2);
            $where['o.pay_time'] = array('between', array($time, $time2));
        }
        if($item_name && $type==1){
            $where['i.item_name'] = ['like','%'.$item_name.'%'];
        }
        $where = isset($where) ? $where : [];
        if ($searchStr) {
            $orderList = Order::alias('o')
                    ->join('custom c', 'c.id = o.ctm_id', 'left')
                    ->join('store s','s.id = o.store_id','left')
                    ->join('ord_pro op','op.ord_id = o.id','left')
                    ->join('item i','i.id = op.pro_id','left')
                    ->where($where)
                    ->where(function ($query) use ($searchStr) {
                        $query->where('c.custom_name', 'like', '%' . $searchStr . '%')
                        ->whereOr('c.custom_phone', 'like', '%' . $searchStr . '%')
                        ->whereOr('o.ord_num', 'like', '%' . $searchStr . '%');
                    })
                    ->field('o.id,o.ord_num,o.status,o.pay_time,o.type,o.pay_money,o.balance_money,o.red_money,o.special_id,c.custom_name,c.custom_phone,c.vip_status,s.store_name,op.pro_id')
                    ->order('o.id desc')
                    ->select();
        } else {
            $orderList = Order::alias('o')
                    ->join('custom c', 'c.id = o.ctm_id', 'left')
                    ->join('store s','s.id = o.store_id','left')
                    ->join('ord_pro op','op.ord_id = o.id','left')
                    ->join('item i','i.id = op.pro_id','left')
                    ->where($where)
                    ->field('o.id,o.ord_num,o.status,o.pay_time,o.type,o.pay_money,o.balance_money,o.red_money,o.special_id,c.custom_name,c.custom_phone,c.vip_status,s.store_name,op.pro_id')
                    ->order('o.id desc')
                    ->select();
        }
        //查询订单购买的项目名称
        foreach ($orderList as $k => $v){
            $type = $v['type'];
            $pro_id = $v['pro_id'];
            //类型 1项目 2超值组合 3充值 4 特权卡5秒杀6体验特权卡7医美项目	
            if($type == 1){
                $item_name = Item::where('id',$pro_id)->value('item_name');
            }elseif ($type == 2) {
                $item_name = Overgroup::where('id',$pro_id)->value('name');
            }elseif ($type == 3) {
                $item_name = '充值';
            }elseif ($type == 4) {
                $item_name = '特权卡';
            }elseif ($type == 5) {
                $miaoshaRow = Miaosha::where('id',$pro_id)->field('name,item_id')->find();
                $item_name = Item::where('id',$miaoshaRow['item_id'])->value('item_name');
                $item_name = $miaoshaRow['name'].'-'.$item_name;
            }elseif ($type == 6) {
                $item_name = '体验特权卡';
            }elseif ($type == 7) {
                $item_name = OrderYimei::alias('y')
                        ->join('item i','i.id = y.item_id','left')
                        ->where('y.ord_id',$v['id'])
                        ->value('i.item_name');
            }
            $orderList[$k]['item_name'] = $item_name;
        }
        
        
        
        $expTitle = '克克美项目订单';
        $expTableData = $orderList;
        
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle . '(-共计' . count($expTableData) . '条)'); //文件名称
        $fileName = $xlsTitle; //or $xlsTitle 文件名称可根据自己情况设定
        if (empty($expTableData)) {
            $this->error('没有符合条件的订单');
        }
        $ii = 3;
        Vendor('PHPExcel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:' . $cellName[13 - 1] . '1'); //合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle . '  Export time:' . date('Y-m-d H:i:s'));
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(18);
        $objPHPExcel->getActiveSheet()->getStyle('A1')->applyFromArray(//居中加粗
                array(
                    'font' => array(
                        'bold' => true
                    ),
                    'alignment' => array(
                        'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                    )
                )
        );
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(30); // 第一行的默认高度
        $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(25); // 第一行的默认高度
        $objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(20); // 所有单元格默认高度
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20); //设置宽width
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER); //垂直居中
        $objPHPExcel->getActiveSheet()->getStyle('2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER); //垂直居中
        $styleArray = array(
            'borders' => array(
                'allborders' => array(
                    //'style' => PHPExcel_Style_Border::BORDER_THICK,//边框是粗的  
                    'style' => \PHPExcel_Style_Border::BORDER_THIN, //细边框  
                //'color' => array('argb' => 'FFFF0000'),  
                ),
            ),
        );
        $objPHPExcel->getActiveSheet()->getStyle('A1:M' . (count($expTableData) + 2))->applyFromArray($styleArray); //这里就是画出从单元格A5到N5的边框，看单元格最右边在哪哪个格就把这个N改为那个字母替代  


        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A2', "编号");
        $objPHPExcel->getActiveSheet()->getStyle('A2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B2', "订单编号");
        $objPHPExcel->getActiveSheet()->getStyle('B2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C2', "项目类型");
        $objPHPExcel->getActiveSheet()->getStyle('C2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D2', "付款时间");
        $objPHPExcel->getActiveSheet()->getStyle('D2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E2', "用户名");
        $objPHPExcel->getActiveSheet()->getStyle('E2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('F2', "下单选店");
        $objPHPExcel->getActiveSheet()->getStyle('F2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('G2', "手机号");
        $objPHPExcel->getActiveSheet()->getStyle('G2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('H2', "支付金额");
        $objPHPExcel->getActiveSheet()->getStyle('H2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('I2', "余额支付");
        $objPHPExcel->getActiveSheet()->getStyle('I2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('J2', "红包支付");
        $objPHPExcel->getActiveSheet()->getStyle('J2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('K2', "订单状态");
        $objPHPExcel->getActiveSheet()->getStyle('K2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('L2', "用户类型");
        $objPHPExcel->getActiveSheet()->getStyle('L2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('M2', "项目名称");
        $objPHPExcel->getActiveSheet()->getStyle('M2')->applyFromArray(array('font' => array('bold' => true)));
        foreach ($expTableData as $key => $val) {
            $tt = 'A' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, " " . $val['id']); //加  “ ”防止用科学计数法，中间必须有空格，否则无效
            $tt = 'B' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, " " . $val['ord_num']);
            $tt = 'C' . $ii;
            if($val['type'] == 1){
                $item_type = '项目';
            }elseif ($val['type'] == 2) {
                $item_type = '超值组合';
            }elseif ($val['type'] == 3) {
                $item_type = '充值';
            }elseif ($val['type'] == 4) {
                $item_type = '特权卡';
            }elseif ($val['type'] == 5) {
                $item_type = '秒杀';
            }elseif ($val['type'] == 6) {
                $item_type = '体验特权';
            }elseif ($val['type'] == 7) {
                $item_type = '医美';
            }
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $item_type);
            $tt = 'D' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['pay_time']);
            $tt = 'E' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['custom_name']);
            $tt = 'F' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['store_name']);
            $tt = 'G' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['custom_phone']);
            $tt = 'H' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['pay_money']/100);
            $tt = 'I' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['balance_money']/100);
            $tt = 'J' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['red_money']/100);
            $tt = 'K' . $ii;
            if($val['status'] == 0){
                $orderStatus = '已取消';
            }elseif ($val['status'] == 1) {
                $orderStatus = '待支付';
            }elseif ($val['status'] == 2) {
                $orderStatus = '已完成';
            }elseif ($val['status'] == 3) {
                $orderStatus = '已退款';
            }
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $orderStatus);
            $tt = 'L' . $ii;
            //	客户类型 0新客户 1普通用户 2特权客户 3体验特权
            if($val['vip_status'] == 0){
                $ctmType = '新客户';
            }elseif ($val['vip_status'] == 1) {
                $ctmType = '普通用户';
            }elseif ($val['vip_status'] == 2) {
                $ctmType = '特权客户';
            }elseif ($val['vip_status'] == 3) {
                $ctmType = '体验特权';
            }
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $ctmType);
            $tt = 'M' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['item_name']);
            $ii++;
        }
        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $fileName . '.xls"');  //日期为文件名后缀
        header('Cache-Control: max-age=0');
        header("Content-type:application/octet-stream");
        header("Accept-Ranges:bytes");
        header("Pragma: no-cache");
        header("Expires: 0");
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }
    
    /*
     * 获取项目详情二维码
     * author xfwed 
     * date 2021.02.26
     */

    public function getItemXcxImg() {
        $rule = [
            'item_id' => 'require',
        ];
        $msg = [
            'item_id.require' => '编号必须',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();
            return Utils::ajaxReturn(1, $error, null);
        }
        
        $itemId = $all['item_id'];
        $key = 'itemid'.$itemId;
        $name = Cache::get($key);
        if ($name) {
             $xcx_img = $name;
        } else {
            //生成项目二维码
            $ApiPath = config('appconfig.ApiPath');
            $postFields['param'] = 'a='.$itemId.'&s=0';
            $postFields['url'] = 'packageA/pages/project/projectDetail/index';
            $relust = Utils::curlPost($ApiPath . '/weChat/getWeChatCodeForUrl/',json_encode($postFields));
            $IndexPath = config('appconfig.IndexPath');
            $relust = json_decode($relust, true)['data'];
            $arr = explode(",", $relust);
            $last = $arr[1];
            $postFields1['img'] = $last;
            $postFields1['modeName'] = 'itemqrcode';
            $relust = Utils::curlPost1($IndexPath.'Public/uploadBase64Img/',$postFields1);
            $relust = json_decode($relust, true)['data'];

            Cache::set($key, $relust);
            $xcx_img = $relust;
        }
      
        return $this->ajaxReturn(0, '获取成功', $xcx_img);
    }
    
    /*
     * 设置/取消特色项目
     * author xfwed
     * date 2021-05-28
     */

    public function setOrCallOffSpecial() {
        $item_id = input('param.item_id');
        $is_special = input('param.is_special');
        $row = Item::where('id',$item_id)->update(['is_special'=>$is_special]);
        if($row){
            return $this->ajaxReturn(0, '操作成功', null);
        }  else {
            return $this->ajaxReturn(3, '操作失败', null);
        }
    }
    
    /*
     * 设置/取消问题项目
     * author xfwed
     * date 2021-08-18
     */

    public function setOrCallOffIssue() {
        $item_id = input('param.item_id');
        $issue_type = input('param.issue_type');
        $row = Item::where('id',$item_id)->update(['issue_type'=>$issue_type]);
        if($row){
            return $this->ajaxReturn(0, '操作成功', null);
        }  else {
            return $this->ajaxReturn(3, '操作失败', null);
        }
    }
    
    /*
     * 设置/取消项目标签
     * author xfwed
     * date 2021-10-13
     */

    public function setOrCallOffTag() {
        $item_id = input('param.item_id');
        $tag = input('param.tag');
        $row = Item::where('id',$item_id)->update(['tag'=>$tag]);
        if($row){
            return $this->ajaxReturn(0, '操作成功', null);
        }  else {
            return $this->ajaxReturn(3, '操作失败', null);
        }
    }

}
